package com.leyou.gateway.filter;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import sun.misc.Request;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author xiuer
 * @description 用户权限，身份过滤器
 * @create 2019/7/9 21:11
 */
@Component
@Slf4j
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class Authfilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FilterProperties filterProperties;

    /**
     * 过滤器的类型 前置
     *
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器的执行顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 是否执行run方法
     * 如果请求路径在白名单内部，那么就不执行run方法。也就是返回false
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String path = ctx.getRequest().getRequestURI();
        boolean result = isAllowPath(path);
        return !result;
    }

    /*判断请求路径是否在白名单中*/
    private boolean isAllowPath(String path) {
        List<String> allowPaths = filterProperties.getAllowPaths();
        for (String allowPath : allowPaths) {
            // 判断前缀是否匹配
            if (path.startsWith(allowPath)) {
                return true;
            }
        }
        //遍历一遍集合都没有 则返回false
        return false;
    }

    /**
     * 过滤器的具体逻辑步骤
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = ctx.getRequest();
        //获取token
        try {
            String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
            //解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            //判断是否在黑名单中
            String cache = redisTemplate.opsForValue().get(payload.getId());
            if (cache != null) {
                throw new RuntimeException("token 已经登出 ，是无效的token");
            }
            //获取用户身份信息
            UserInfo userInfo = payload.getUserInfo();
            String role = userInfo.getRole();
            //获取当前资源路径
            String path = request.getRequestURI();
            String method = request.getMethod();
            //TODO 权限控制未做
            log.info("【网关微服务】用户{},角色{}。访问服务{} : {}，", userInfo.getUsername(), role, method, path);
        } catch (Exception e) {
            //拦截用户请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);  //没有授权禁止访问Forbidden
            log.error("非法访问，未登录，地址：{}", request.getRemoteHost(), e);
        }
        return null;
    }
}
